package com.tom.angel.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
	
	/**
	 * 创建Session对象
	 */
	private static Session session;
	
	/**
	 * 创建SessionFactory的对象
	 */
	private static SessionFactory sessionFactory = null;
	
	/**
	 * 创建hibernate4中的ServiceRegistry对象
	 */
	private static ServiceRegistry serviceRegistry;
	
	/**
	 * 静态的方法获取SessionFactory的对象
	 * @return
	 */
	public static Session getSession(){
		
		//定义Configuration对象
		Configuration configuration = new Configuration();
		
		configuration.configure();
		
		//获取serviceRegistry的对象
		serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
		try {
			//获取sessionFactory对象
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
			//获取Session对象
			session = sessionFactory.openSession();
		} catch (Exception e) {
			//Log4j打印异常语句
			Log4jUntil.outPutLog(SessionFactory.class, "获取SessionFactory失败"+e.getMessage());
		}
		//返回session对象
		return session;
	}
}
